<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组去重</title>
</head>

<body>
    <script>
        //输入[1,5,2,3,6,3,2] 

        //数组本身去重
        function unique(array) {
            for (let i = 0; i < array.length; i++) {
                for (let j = i + 1; j < array.length; j++) {
                    if (array[i] === array[j]) {
                        array.splice(j, 1);
                        j--
                    }
                }
            }
        }
        let array = [1, 5, 2, 3, 6, 3, 2];
        unique(array);
        console.log('unique', array);//[1, 5, 2, 3, 6]


        //数组本身不去重
        // 1.Set方式
        function unique1(array1) {
            console.log(new Set(array1))//Set(5) {1, 5, 2, 3, 6}
            //(1)方式1
            return [...new Set(array1)]
            //(2)方式2：Array.from可以创建新的、浅拷贝的数组
            return Array.from(new Set(array1))
        }
        const array1 = [1, 5, 2, 3, 6, 3, 2];
        let result1 = unique1(array1);
        console.log('unique1', result1);//[1, 5, 2, 3, 6]

        // 2.通过 includes 判断的方式
        function unique2(array2) {
            return array2.reduce((accu, cur) => {
                if (!accu.includes(cur)) {
                    accu.push(cur)
                }
                return accu
            }, [])
        }
        const array2 = [1, 5, 2, 3, 6, 3, 2];
        let result2 = unique2(array2);
        console.log('unique2', result2);//[1, 5, 2, 3, 6]

        // 3.object.values（这种方式会直接按照索引进行升序）
        function unique3(array3) {
            let result = array3.reduce((accu, cur) => {
                if (!accu[cur]) {
                    accu[cur] = cur;
                }
                return accu
            }, {})
            console.log(result);//{1: 1, 2: 2, 3: 3, 5: 5, 6: 6}
            //Object.values
            return Object.values(result)
        }
        const array3 = [1, 5, 2, 3, 6, 3, 2];
        let result3 = unique3(array3);
        console.log('unique3', result3);//[1, 2, 3, 5, 6]
    </script>
</body>

</html>